package dao

import (
	"yundian/internel/app/models/orders"
	"yundian/internel/pkg/dingo"
	"yundian/internel/pkg/dingo/global"
	"yundian/internel/pkg/wechatpay"
)

// GetOrderInfoByTradeNo 获取订单详情
func (d *OrderDao) GetOrderInfoByTradeNo(tradeNo string) *dingo.ErrorWrap {
	m := orders.New()
	sql := "select * from orders where trade_no = ? limit 1"
	db := global.Orm.Raw(sql, tradeNo).Find(&m)
	return dingo.ErrorIf(db.Error, m)
}

// GetOrderInfoByTradeNo 获取订单详情
func (d *OrderDao) GetLimitOneOrderInfoByTradeNo(tradeNo string) *dingo.ErrorWrap {
	m := orders.New()
	sql := "select * from orders where trade_no = ?"
	db := global.Orm.Raw(sql, tradeNo).Find(&m).Limit(1)
	return dingo.ErrorIf(db.Error, m)
}

// 微信密码页面获取订单详情
func (d *OrderDao) WxGetOrderInfoByTradeNo(tradeNo string) *dingo.ErrorWrap {
	m := orders.New()
	sql := "select * from orders where trade_no = ? order by create_at desc"
	db := global.Orm.Raw(sql, tradeNo).Find(&m).Limit(1)
	return dingo.ErrorIf(db.Error, m)
}

// GetOrderInfoByOpenidAndSn 获取订单下在进行中的订单信息
func (d *OrderDao) GetOrderInfoByOpenidAndSn(openid, deviceSn string) *dingo.ErrorWrap {
	m := orders.New()
	sql := "select * from orders where state = 2 and openid = ? and device_sn = ?"
	db := global.Orm.Debug().Raw(sql, openid, deviceSn).Find(&m)
	return dingo.ErrorIf(db.Error, m)
}

func (d *OrderDao) GetOrderInfoByTradeNoAndCreateTime(tradeNo, createTime string) *dingo.ErrorWrap {
	m := orders.New()
	//sql := "select * from orders where trade_no = ? and create_time = ?"
	//db := global.Orm.Raw(sql, tradeNo, createTime).Find(&m)
	db := global.Orm.Table("orders").
		Where("trade_no = ?", tradeNo).
		Where("create_at = ?", wechatpay.StrTimeToInt(createTime)).
		Find(&m)
	return dingo.ErrorIf(db.Error, m)
}

func (d *OrderDao) GetOrderInfoByOutTradeNo(tradeNo string) *dingo.ErrorWrap {
	m := orders.New()
	sql := "select * from orders where out_trade_no = ?"
	db := global.Orm.Raw(sql, tradeNo).Find(&m)
	return dingo.ErrorIf(db.Error, m)
}

// GetOrderInfoByOpenidAndSn 获取当前用户在进行中的订单信息
func (d *OrderDao) GetOrderInfoByOpenid(openid string) *dingo.ErrorWrap {
	m := orders.New()
	sql := "select * from orders where state = 2 and openid = ? "
	db := global.Orm.Debug().Raw(sql, openid).Find(&m)
	return dingo.ErrorIf(db.Error, m)
}
